import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, message, Collapse, Divider} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE, FORM_BIG_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import styles from './style.css';
import Return from '../common/Return';
import {validateUpdate} from './utils';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import DetailTable from './DetailTable';
import FileUpload from './FileUpload';
import {cabinetType, packingType} from '../Enum';
import {conventEnumValueToString} from '../utils';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];

const Panel = Collapse.Panel;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    onSubmit = () => {
        const result = validateUpdate(this.props.conditions);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onChangeCollapse = key => {
        this.setState({
            currentPanelId: key
        });
    }

    onChangeUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.updateAttachments(data);
    }

    render() {
        const {details = [], attachments = []} = this.props.conditions;
        const packingPanel = details.map(p => {
            const header = (
                <Row>
                    <Col span={4} className={styles.edit}>
                        <Ellipsis tooltip fullWidthRecognition length={36}>{p.pickingListCodes}</Ellipsis>
                    </Col>
                    <Col span={20} className={styles.edit}>
                        {`${this.props.intl.formatMessage({
                            id: 'update.info.workKind',
                            defaultMessage: '包装类型/规格'
                        })}: ${conventEnumValueToString(packingType, p.packingType)} / ${p.container}`}
                    </Col>
                </Row>
            );
            const dataSource = p.packingListDetails || EMPTY_ARRAY;
            return (
                <Panel key={p.packingListId} header={header} >
                    <Row className="form-standard">
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'update.form.length',
                                    defaultMessage: '长度（mm）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.length}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'update.form.width',
                                    defaultMessage: '宽度（mm）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.width}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'update.form.height',
                                    defaultMessage: '高度（mm）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.height}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'update.form.volume',
                                    defaultMessage: '体积（m³）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.volume}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'update.form.netWeight',
                                    defaultMessage: '净重（kg）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.netWeight}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'update.form.grossWeight',
                                    defaultMessage: '毛重（kg）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.grossWeight}</span>
                            </FormItem>
                        </Col>
                    </Row>
                    <DetailTable data={dataSource} loading={this.state.tableLoading} />
                </Panel>
            );
        });
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'update.card.title',
                                defaultMessage: '排柜单信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{`(${this.props.conditions.dealerCode})${this.props.conditions.dealerName}`}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'update.form.country',
                                            defaultMessage: '国家/地区'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.country}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.containerNo ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'update.form.containerNo',
                                            defaultMessage: '柜图号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="containerNo"
                                            value={this.props.conditions.containerNo} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.cabinetType ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'update.form.cabinetType',
                                            defaultMessage: '柜型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            name="cabinetType"
                                            value={this.props.conditions.cabinetType}
                                            options={cabinetType.toList(language)}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'update.details.title',
                                defaultMessage: '排柜单清单'
                            })}
                            bordered={false}>
                            <Collapse accordion onChange={this.onChangeCollapse}>
                                {packingPanel}
                            </Collapse>
                        </Card>
                        <Card title={this.props.intl.formatMessage({
                            id: 'update.card.fileList.title',
                            defaultMessage: '附件清单'
                        })}>
                            <Row>
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload} onRemove={this.props.removeAttachments} fileList={attachments} />
                                </Col>
                            </Row>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {this.props.intl.formatMessage({
                                                id: 'update.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    updateAttachments,
    removeAttachments,
    onClickUpdate,
    getDetail,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    permissions => {
        const data = permissions.toJS();
        return data.includes(PERMISSION.add);
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onClickUpdate(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    updateAttachments: data => dispatch(updateAttachments(data)),
    removeAttachments: ({id}) => dispatch(removeAttachments(id)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
